package pe.gob.onpe.facade;

import java.util.List;
import java.util.logging.Level;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import pe.gob.onpe.ejb.LogUtil;
import pe.gob.onpe.ejb.Parametro;
import pe.gob.onpe.facade.local.ParametroFacadeLocal;
import pe.gob.onpe.facade.remote.ParametroFacadeRemote;

@Stateless
public class ParametroFacade implements ParametroFacadeLocal, ParametroFacadeRemote {

	public static final String NOMBRE		= "nombre";
	public static final String VALORMINIMO	= "valorminimo";
	public static final String VALORMAXIMO	= "valormaximo";

	@PersistenceContext
	private EntityManager entityManager;

	/**
	 * Perform an initial save of a previously unsaved Parametro entity. All
	 * subsequent persist actions of this entity should use the #update()
	 * method.
	 * 
	 * @param entity
	 *            Parametro entity to persist
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void save(Parametro entity) {
		LogUtil.log("saving Parametro instance", Level.INFO, null);
		try {
			entityManager.persist(entity);
			LogUtil.log("save successful", Level.INFO, null);
		} catch (RuntimeException re) {
			LogUtil.log("save failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * Delete a persistent Parametro entity.
	 * 
	 * @param entity
	 *            Parametro entity to delete
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void delete(Parametro entity) {
		LogUtil.log("deleting Parametro instance", Level.INFO, null);
		try {
			entity = entityManager.getReference(Parametro.class, entity
					.getParametroId());
			entityManager.remove(entity);
			LogUtil.log("delete successful", Level.INFO, null);
		} catch (RuntimeException re) {
			LogUtil.log("delete failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * Persist a previously saved Parametro entity and return it or a copy of it
	 * to the sender. A copy of the Parametro entity parameter is returned when
	 * the JPA persistence mechanism has not previously been tracking the
	 * updated entity.
	 * 
	 * @param entity
	 *            Parametro entity to update
	 * @returns Parametro the persisted Parametro entity instance, may not be
	 *          the same
	 * @throws RuntimeException
	 *             if the operation fails
	 */
	public Parametro update(Parametro entity) {
		LogUtil.log("updating Parametro instance", Level.INFO, null);
		try {
			Parametro result = entityManager.merge(entity);
			LogUtil.log("update successful", Level.INFO, null);
			return result;
		} catch (RuntimeException re) {
			LogUtil.log("update failed", Level.SEVERE, re);
			throw re;
		}
	}

	public Parametro findById(Long id) {
		LogUtil.log("finding Parametro instance with id: " + id, Level.INFO,
				null);
		try {
			Parametro instance = entityManager.find(Parametro.class, id);
			return instance;
		} catch (RuntimeException re) {
			LogUtil.log("find failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * Find all Parametro entities with a specific property value.
	 * 
	 * @param propertyName
	 *            the name of the Parametro property to query
	 * @param value
	 *            the property value to match
	 * @param rowStartIdxAndCount
	 *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
	 *            row index in the query result-set to begin collecting the
	 *            results. rowStartIdxAndCount[1] specifies the the maximum
	 *            number of results to return.
	 * @return List<Parametro> found by query
	 */
	@SuppressWarnings("unchecked")
	public List<Parametro> findByProperty(String propertyName,
			final Object value, final int... rowStartIdxAndCount) {
		LogUtil.log("finding Parametro instance with property: " + propertyName
				+ ", value: " + value, Level.INFO, null);
		try {
			final String queryString = "select model from Parametro model where model."
					+ propertyName + "= :propertyValue";
			Query query = entityManager.createQuery(queryString);
			query.setParameter("propertyValue", value);
			if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
				int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
				if (rowStartIdx > 0) {
					query.setFirstResult(rowStartIdx);
				}

				if (rowStartIdxAndCount.length > 1) {
					int rowCount = Math.max(0, rowStartIdxAndCount[1]);
					if (rowCount > 0) {
						query.setMaxResults(rowCount);
					}
				}
			}
			return query.getResultList();
		} catch (RuntimeException re) {
			LogUtil.log("find by property name failed", Level.SEVERE, re);
			throw re;
		}
	}

	public List<Parametro> findByNombre(Object nombre,
			int... rowStartIdxAndCount) {
		return findByProperty(NOMBRE, nombre, rowStartIdxAndCount);
	}

	public List<Parametro> findByValorminimo(Object valorminimo,
			int... rowStartIdxAndCount) {
		return findByProperty(VALORMINIMO, valorminimo, rowStartIdxAndCount);
	}

	public List<Parametro> findByValormaximo(Object valormaximo,
			int... rowStartIdxAndCount) {
		return findByProperty(VALORMAXIMO, valormaximo, rowStartIdxAndCount);
	}

	/**
	 * Find all Parametro entities.
	 * 
	 * @param rowStartIdxAndCount
	 *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
	 *            row index in the query result-set to begin collecting the
	 *            results. rowStartIdxAndCount[1] specifies the the maximum
	 *            count of results to return.
	 * @return List<Parametro> all Parametro entities
	 */
	@SuppressWarnings("unchecked")
	public List<Parametro> findAll(final int... rowStartIdxAndCount) {
		LogUtil.log("finding all Parametro instances", Level.INFO, null);
		try {
			final String queryString = "select model from Parametro model";
			Query query = entityManager.createQuery(queryString);
			if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
				int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
				if (rowStartIdx > 0) {
					query.setFirstResult(rowStartIdx);
				}

				if (rowStartIdxAndCount.length > 1) {
					int rowCount = Math.max(0, rowStartIdxAndCount[1]);
					if (rowCount > 0) {
						query.setMaxResults(rowCount);
					}
				}
			}
			return query.getResultList();
		} catch (RuntimeException re) {
			LogUtil.log("find all failed", Level.SEVERE, re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Parametro> buscarPorTipo(String tipoParametro) {
		Query query = entityManager.createQuery("SELECT p FROM " +
												"Parametro p " +
												"where " +
												"p.tipoParametro = :tipoParametro ");
		query.setParameter("tipoParametro", tipoParametro);
		List<Parametro> listParametro =  query.getResultList();
		return listParametro;
	}	
}